package com.gomore.opple.module.addaddress;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gomore.opple.R;
import com.gomore.opple.model.EventReflahAddress;
import com.gomore.opple.module.BaseFragment;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.utils.DialogUtils;
import com.gomore.opple.web.cgform.shippingaddr.entity.TOShippingAddrEntity;
import com.gomore.opple.widgets.dialog.ConfirmDialog;
import com.lljjcoder.citypickerview.widget.CityPicker;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;


/**
 * Created by robot
 */
public class AddAddressFragment extends BaseFragment implements AddAddressContract.View {
    @Bind(R.id.back)
    LinearLayout back;
    @Bind(R.id.delete)
    TextView delete;
    @Bind(R.id.consumer_name)
    EditText consumer_name;
    @Bind(R.id.consumer_mobile)
    EditText consumer_mobile;
    @Bind(R.id.select_zone)
    TextView select_zone;
    @Bind(R.id.consumer_address)
    EditText consumer_address;
    @Bind(R.id.save)
    TextView save;
    private AddAddressContract.Presenter mPresenter;
    String province, citys, country;
    TOShippingAddrEntity toShippingAddrEntity;

    public static AddAddressFragment getInstance() {
        return new AddAddressFragment();
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_add_address;
    }

    @Override
    protected void initalizeData() {
        if (getArguments() != null) {
            toShippingAddrEntity = (TOShippingAddrEntity) getArguments().getSerializable(IntentStart.ADDRESS);
        }
    }

    @Override
    protected void initalizeViews() {
        mPresenter.prepareInitData();
        if (toShippingAddrEntity == null) {
            delete.setVisibility(View.GONE);
            toShippingAddrEntity = new TOShippingAddrEntity();
        } else {
            showContent(toShippingAddrEntity);
        }
    }


    @Override
    public void setPresenter(AddAddressContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showProgressDialog() {
        DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }

    @Override
    public void backToAccount() {
        EventReflahAddress eventReflahAddress = new EventReflahAddress();
        eventReflahAddress.setReflash(true);
        EventBus.getDefault().post(eventReflahAddress);
        getActivity().finish();
    }

    @OnClick({R.id.select_zone, R.id.back, R.id.delete, R.id.save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.select_zone:
                //收起软键盘
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                ZonePicker();
                break;
            case R.id.back:
                getActivity().finish();
                break;
            case R.id.delete:
                delete();
                break;
            case R.id.save:
                save();
                break;
        }
    }


    private void ZonePicker() {
        CityPicker cityPicker = new CityPicker.Builder(getActivity())
                .textSize(20)
                .title("地址选择")
                .backgroundPop(0xa0000000)
                .titleBackgroundColor("#cccccc")
                .titleTextColor("#000000")
                .confirTextColor("#666666")
                .cancelTextColor("#666666")
                .province("江苏省")
                .city("常州市")
                .district("天宁区")
                .textColor(Color.parseColor("#666666"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(5)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();

        //监听方法，获取选择结果
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                province = citySelected[0];
                //城市
                citys = citySelected[1].replace(" ", "");
                //区县（如果设定了两级联动，那么该项返回空）
                country = citySelected[2];
                //邮编
                String code = citySelected[3];
                select_zone.setText(province + "-" + citys + "-" + country);
            }

            @Override
            public void onCancel() {
//                Toast.makeText(getActivity(), "已取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showContent(TOShippingAddrEntity toShippingAddrEntity) {
        if (toShippingAddrEntity.getName() != null) {
            consumer_name.setText(toShippingAddrEntity.getName());
            consumer_name.setSelection(toShippingAddrEntity.getName().length());
        }
        if (toShippingAddrEntity.getMiblephone() != null) {
            consumer_mobile.setText(toShippingAddrEntity.getMiblephone());
            consumer_mobile.setSelection(toShippingAddrEntity.getMiblephone().length());
        }
        if (toShippingAddrEntity.getProvince() != null) {
            province = toShippingAddrEntity.getProvince();
            citys = toShippingAddrEntity.getCity();
            country = toShippingAddrEntity.getCountry();
            select_zone.setText(province + " - " + citys + " - " + country);
        }
        if (toShippingAddrEntity.getAddress() != null) {
            consumer_address.setText(toShippingAddrEntity.getAddress());
        }
    }

    private void save() {
        if (TextUtils.isEmpty(consumer_name.getText().toString().trim())) {
            showMessage("请填写客户姓名");
            return;
        }
        if (TextUtils.isEmpty(consumer_mobile.getText().toString().trim())) {
            showMessage("请填写手机号码");
            return;
        }
        if (!isPhoneNumberValid(consumer_mobile.getText().toString().trim())) {
            showMessage("请填写正确格式手机号码");
            return;
        }
        if (TextUtils.isEmpty(province)) {
            showMessage("请选择省市区");
            return;
        }
        if (TextUtils.isEmpty(consumer_address.getText().toString().trim())) {
            showMessage("请填写客户地址");
            return;
        }
        toShippingAddrEntity.setName(consumer_name.getText().toString().trim());
        toShippingAddrEntity.setMiblephone(consumer_mobile.getText().toString().trim());
        toShippingAddrEntity.setProvince(province);
        toShippingAddrEntity.setCity(citys);
        toShippingAddrEntity.setCountry(country);
        toShippingAddrEntity.setAddress(consumer_address.getText().toString().trim());
        //确定框
        ConfirmDialog.onNoOnclickListener onNoOnclickListener = null;
        ConfirmDialog.onYesOnclickListener onYesOnclickListener = null;
        final String title = "提示";
        String message = "确定保存收货人地址吗?";
        onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                if (toShippingAddrEntity.getId() == null) {
                    if (mPresenter.getConsumer() != null) {
                        toShippingAddrEntity.setConsumerId(mPresenter.getConsumer().getId());
                        mPresenter.saveAddress(toShippingAddrEntity);
                    }
                } else {
                    mPresenter.updateAddress(toShippingAddrEntity);
                }
            }
        };
        onNoOnclickListener = new ConfirmDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                DialogUtils.cancel();
            }
        };
        DialogUtils.showConfirmDialog(getActivity(), onYesOnclickListener, onNoOnclickListener, title, message);
    }

    private void delete() {
        if (toShippingAddrEntity.getId() != null) {
            //确定框
            ConfirmDialog.onNoOnclickListener onNoOnclickListener = null;
            ConfirmDialog.onYesOnclickListener onYesOnclickListener = null;
            final String title = "提示";
            String message = "确定删除收货人地址吗?";
            onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    mPresenter.removeAddress(toShippingAddrEntity.getId());
                }
            };
            onNoOnclickListener = new ConfirmDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    DialogUtils.cancel();
                }
            };
            DialogUtils.showConfirmDialog(getActivity(), onYesOnclickListener, onNoOnclickListener, title, message);
        }
    }

    //判断是否为电话号码
    private boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;
        String expression = "((^(13|14|15|17|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }
}
